<template>
  <div class="qcStandarAddcon" v-if="addVisible">
    <div>
      <div class="twoStageWindow">
        <div class="twoStageWindowTitle">
          {{newOrEdit=='new'?'新增':(newOrEdit=='edit'?'编辑':(newOrEdit=='look'?'查看':'复制'))}}质控类型
          <div class="twoStageWindowClose">
            <el-button size="mini" type="primary" @click="submitQctype('commit')" v-if="newOrEdit != 'look'" :disabled="!isRepeat">提 交</el-button>
            <el-button size="mini" type="primary" @click="submitQctype('save')" v-if=" newOrEdit == 'new' || (isStatus == 2 && newOrEdit != 'look')"
              :disabled="!isRepeat">保 存</el-button>
            <el-button size="mini" @click="close()">取消</el-button>
          </div>
        </div>
        <div class="containercontent" style="margin-top:40px;height:calc(100% - 40px);padding-top: 0;">
          <div class="form">

            <el-form label-width="110px" :inline="false" class="demo-form-inline" :model="sisForm" :rules="rules" ref="sisForm">
              <el-form-item label="名称" prop="name">
                <el-col :span="22">
                  <el-input placeholder="质控类型名称" size="mini" v-model="sisForm.name" :disabled="newOrEdit == 'look'"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="分类" prop="genre" class = "qctypeVail errorVail">
                <el-col :span="22">
                  <el-cascader :options="qcGenre" v-model="outGenre" size="mini" style="width:100%;" :disabled="newOrEdit == 'look'" @change = "selectQC">
                  </el-cascader>
                  <div class="el-form-item__error" v-if="genreError">
                    请选择分类
                  </div>
                </el-col>
              </el-form-item>
              <el-form-item label="质控类别" prop="type">
                <el-col :span="22">
                <el-select v-model="sisForm.type" placeholder="请选择" style="width: 100%;" size="mini" :disabled="newOrEdit == 'look'" >
                  <el-option v-for="item in typeOption" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
                </el-col>
              </el-form-item>
              <el-form-item label="分组" prop="group">
                <el-col :span="22">
                <el-select v-model="sisForm.group" placeholder="请选择" style="width: 100%;" size="mini" :disabled="newOrEdit == 'look'" >
                  <el-option v-for="item in groupOption" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
                </el-col>
              </el-form-item>
						
              <el-form-item label="空间位置" prop="space">
                <el-col :span="22">
                <el-select v-model="sisForm.space" placeholder="请选择" style="width: 100%;" size="mini" :disabled="newOrEdit == 'look'" >
                  <el-option v-for="item in spaceOption" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
                </el-col>
              </el-form-item>
              <el-form-item label="状态" v-if="newOrEdit != 'new'">
                <el-col :span="22">
                  <el-select v-model="sisForm.status" placeholder="请选择" style="width: 100%;" size="mini" disabled>
                    <el-option v-for="item in enableStatus" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-col>
              </el-form-item>
            </el-form>
          </div>
          <div class="elTab">
            <el-tabs style="width: 100%;">
              <el-tab-pane label="质控参数">
                <el-button size="mini" type="primary" @click="choseQcStandar()" v-if="newOrEdit != 'look'"
                  style="float:right;margin-bottom:8px;">添加质控参数</el-button>
                <el-table :data="qcStandarTableData" style="width: 100%" size="mini" class="tableCon">

                  <el-table-column label="序号" fixed min-width="50px">
                    <!--<template slot-scope="scope">
                      <div class="yangpinbeihao">
                        {{scope.$index+1}}
                        <div class="yangpinyidong" @click="shangyi(scope.row,scope.$index)">
                          <i class="el-icon-arrow-up"></i>
                        </div>
                        <div class="yangpinyidong" @click="xiayi(scope.row,scope.$index)">
                          <i class="el-icon-arrow-down"></i>
                        </div>
                      </div>
                    </template>-->
                    <template slot-scope="scope">
                      {{scope.$index+1}}
                    </template>
                  </el-table-column>
                  <el-table-column property="normName" :show-overflow-tooltip="true" label="名称" min-width="100px">
                  </el-table-column>
                  <el-table-column property="inputType" label="文本类型" :formatter="inputFormatter" min-width="100px">
                  </el-table-column>
                  <el-table-column property="unitName" label="单位" min-width="100px">
                  </el-table-column>
                  <el-table-column property="genre" label="分类" :formatter="genreFormatter" min-width="100px">
                  </el-table-column>
                  <el-table-column property="doDisplay" label="是否展示" min-width="100px" v-if="sisForm.source !='' || sisForm.source != undefined ">
                    <template slot-scope="scope">
                      <el-switch v-model="scope.row.doDisplay" active-text="是" inactive-text="否">
                      </el-switch>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" min-width="100px" v-if="newOrEdit != 'look'">
                    <template slot-scope="scope">
                      <el-button @click.native="deleteQcStandar(scope.$index)" type="text" size="mini">删除</el-button>
                      <el-button @click.native="ascQcStandar(scope.row,scope.$index)" type="text" size="mini">上移</el-button>
                      <el-button @click.native="descQcStandar(scope.row,scope.$index)" type="text" size="mini">下移</el-button>
                    </template>
                  </el-table-column>
                </el-table>

              </el-tab-pane>
            </el-tabs>
          </div>

        </div>
        <div class="user-footer" v-if="newOrEdit == 'look'">
          <span>
                创建人:{{sisForm.createBy}} 
              </span>
          <span>
                创建时间:{{sisForm.createTime}} 
              </span>
          <span v-if="sisForm.updateBy != undefined">
                修改人：{{sisForm.updateBy}} 
              </span>
          <span v-if="sisForm.updateTime != undefined">
                修改时间：{{sisForm.updateTime}} 
              </span>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="qcStandarShow" @close="resetTable" width="70%" :show-close='false' class="addqcStandarDialog" :closeOnClickModal='false'>
      <span slot="title" class="dialog-title">
		  	选择质控参数
			<el-button  size="mini" @click="qcStandarShow = false" class="popupClose">关闭</el-button>
		</span>
      <div class="selectw100 seachTip">
        <div class="inlineblock verticalmiddle infoitem">
          <div class="inlineblock verticalmiddle">
            名称
          </div>
          <div class="inlineblock verticalmiddle informationItem">
            <el-input style="" v-model="qcStandarName" size="mini" placeholder="质控参数名称" @keyup.enter.native="getQcStandar(null)"></el-input>
          </div>
        </div>
        <div class="inlineblock basicRightDistanceA searchIcon">
          <el-button size="mini" @click="getQcStandar(null)">搜索</el-button>
        </div>

      </div>
      <div class="heighHalf">
        <el-table :data="choseqcStandarData" style="width: 100%" size="mini" ref="multipleTable" class="tableCon" @selection-change="handleSelectionChange">
          <el-table-column fixed type="selection" width="38px">
          </el-table-column>
          <el-table-column label="序号" fixed min-width="50px">
            <template slot-scope="scope">
              {{scope.$index+1}}
            </template>
          </el-table-column>
          <el-table-column property="name" :show-overflow-tooltip="true" label="名称" min-width="100px">
          </el-table-column>
          <el-table-column property="inputType" label="文本类型" :formatter="inputFormatter" min-width="100px">
          </el-table-column>
          <el-table-column property="unitName" label="单位" min-width="100px">
          </el-table-column>
          <el-table-column property="genre" label="分类" :formatter="genreFormatter" min-width="100px">
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
			<el-button type="primary" size="mini" @click="subQcStandar">确 定</el-button>
			<el-button  size="mini" @click="resetTable">取 消</el-button>
		</span>
    </el-dialog>


  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import $ from 'jquery'



  export default {
    data() {
      const that = this;
      return {
        sisForm: {
          name: '',
          status: 1,
          genre: null,
          group: null,
          code: null,
          type:null,
          space:null
        },
        rules: {	//表单验证的规则
          name: [
            { type: 'string', required: true, message: '请填写名称', trigger: 'blur' }
          ],
          group:[{ required: true, message: '请选择分组', trigger: 'change' }],
          type:[{required: true, message: '请选择质控类别', trigger: 'change' }],
          space:[{required: true, message: '请选择空间位置', trigger: 'change' }],
          // genre:[{ required: true, message: '请选择分类', trigger: 'change' }]
        },
        qcStandarTableData: [],
        choseqcStandarData: [],
        multipleData: [],
        outGenre: [],  //分类绑定的值
        qcStandarShow: false, //质控指标
        inputSelect: [{
          label: '文本型',
          value: 1,
        }, {
          label: '输入型',
          value: 2,
        }, {
          label: '选择型',
          value: 3,
        }],
        genreSelect: [
          {
            label: '公共参数',
            value: 1,
          }, {
            label: '质控参数',
            value: 2,
          }
        ],
       
        isStatus: null,
        qcStandarName: null,
        isRepeat: true,
        genreError:false,

      }
    },
    props: ['newOrEdit', 'addVisible', 'QcTypeDetail'],
    components: {

    },
    computed: {
      ...mapState(['enableStatus', 'qcGenre', 'sampleType', 'bottleOptions', 'groupSelect', 'abilityTableDate', 'yesorno', 'unitTableDate', 'ruleSelect', 'dataSelect','groupOption','typeOption','spaceOption']),
      analytableHeight() {
        return 500
      }
    },
    mounted() {
      this.$store.dispatch("getAllBottles");
    },
    watch: {
      qcStandarShow(val, oldVal) {
        if (val) {
          this.getQcStandar(null);
        }
      },
      addVisible(val, oldVal) {
        // if (val && this.newOrEdit == 'new') {
        //   this.getQcStandar(1);
        // }
      },
      QcTypeDetail() {
        for (var i in this.QcTypeDetail) {
          this.sisForm[i] = this.QcTypeDetail[i]
        }
        this.isStatus = this.sisForm.status;
        this.qcStandarTableData = this.sisForm.typeNormBeans
        this.changeGenre()
      },


    },
    methods: {
      ascQcStandar(row, index) { //上移
        if (index == 0) {
          return
        } else {
          this.qcStandarTableData.splice(index - 1, 0, this.qcStandarTableData[index]) //把点击的这一行插入到上一条
          this.qcStandarTableData.splice(Number(index) + 1, 1) //插入成功之后删除该条 坐标为index + 1
        
          this.sortQctype(this.qcStandarTableData);
        }

      },
      descQcStandar(row, index) { //下移

        if (index == this.qcStandarTableData.length - 1) {
          return
        } else {
          this.qcStandarTableData.splice(index + 2, 0, this.qcStandarTableData[index]) //把点击的这一行插入当前坐标加2的位置
          this.qcStandarTableData.splice(index, 1) //删除该条
        }

        this.sortQctype(this.qcStandarTableData);
      },
      sortQctype(arr) {
        this.$http({
          method: 'post',
          apiUrl: "/qc/updateNormBySort.htm",
          params: arr,
          isJson: true,
        }).then(res => {
            
        })
      },

      genreFormatter(row, column, cellValue, index) {
        return this.util.changeStatus({ cellValue: cellValue, list: this.genreSelect })
      },
      // 级联选择器转换
      getTreeDeepArr(key, treeData) {
        let arr = []; // 在递归时操作的数组
        let returnArr = []; // 存放结果的数组
        let depth = 0; // 定义全局层级
        // 定义递归函数
        function childrenEach(childrenData, depthN) {
          for (var j = 0; j < childrenData.length; j++) {
            depth = depthN; // 将执行的层级赋值 到 全局层级
            arr[depthN] = (childrenData[j].value);
            if (childrenData[j].value == key) {
              // returnArr = arr; // 原写法不行, 因 此赋值存在指针关系
              returnArr = arr.slice(0, depthN + 1); //将目前匹配的数组，截断并保存到结果数组，
              break
            } else {
              if (childrenData[j].children) {
                depth++;
                childrenEach(childrenData[j].children, depth);
              }
            }
          }
          return returnArr;
        }
        return childrenEach(treeData, depth);
      },
      changeGenre() {
        this.outGenre = this.getTreeDeepArr(this.sisForm.genre, this.qcGenre)
      },
       selectQC(){
         $('.qctypeVail.errorVail').addClass('is-success').removeClass('is-error')
        this.genreError = false;
      },
      // 转换文本类型数据
      inputFormatter(row, column, cellValue, index) {
        return this.util.changeStatus({ cellValue: cellValue, list: this.inputSelect })
      },
      // 保存编辑或者修改
      submitQctype(value) {
        this.$refs.sisForm.validate((valid) => { //表单验证
          if (valid) {
            if(this.outGenre.length ==0){
              $('.qctypeVail.errorVail').addClass('is-error')
              this.genreError = true;
              return;
            }
            var data = {
              name: this.sisForm.name,
              space:this.sisForm.space,
              type:this.sisForm.type,
              group:this.sisForm.group,
              genre: this.outGenre[this.outGenre.length - 1],
              typeNormBeans: this.qcStandarTableData,

            }
            if (this.newOrEdit == 'new') {
              var url = '/qc/addQcType.htm'

              if (value == 'commit') {
                data.status = 1
              } else {
                data.status = 2
              }
            } else {
              var url = '/qc/updateQcType.htm'
              data.id = this.sisForm.id
              data.code = this.sisForm.code
              if (value == 'commit') {
                data.status = 1
              }
            }
            this.isRepeat = false;
            this.$http({
              method: 'post',
              apiUrl: url,
              params: data,
              isJson: true,
            }).then(res => {
              this.isRepeat = true;
              if (res.code == 0) {
                this.$message({
                  type: 'success',
                  message: '提交成功!'
                });
                this.close()
                this.$parent.readQcType(this.$parent.readQuery)
              }

            }).catch(() => {

            });
          }else{
              $('.qctypeVail.errorVail').addClass('is-error')
              this.genreError = true;
              return;
          }
        })



      },
      // 选择质控指标弹出
      choseQcStandar() {
        this.qcStandarShow = true
      },
      // 读取要选择的质控指标
      getQcStandar(genre) {
        this.$http({
          method: 'post',
          apiUrl: '/qc/readQcNorms.htm',
          params: {
            name: this.qcStandarName,
            genre: genre
          },
          isJson: false
        }).then(res => {
          if (res.code === 0) {

            if (genre == 1) {
              for (var i in res.data) {
                res.data[i].normCode = res.data[i].code
                res.data[i].normName = res.data[i].name
                res.data[i].doDisplay = true;
              }
              this.qcStandarTableData = res.data;
            } else {
              this.choseqcStandarData = res.data;
            }

          }

        })
      },
      // 勾选的质控指标
      handleSelectionChange(val) {
        this.multipleData = val
      },
      // 把选中的质控指标加入到已指标，并去重
      subQcStandar() {
        for (var i in this.multipleData) {
          this.multipleData[i].normCode = this.multipleData[i].code
          this.multipleData[i].normName = this.multipleData[i].name
          this.multipleData[i].doDisplay = true;
        }
        this.qcStandarTableData = this.util.repeatData({ old: this.qcStandarTableData, new: this.multipleData, unique: 'normCode' })
        this.resetTable();
      },
      // 删除质控指标
      deleteQcStandar(index) {
        this.qcStandarTableData.splice(index, 1)
      },
      // 关闭添加或者修改弹框
      close() {
        this.$refs.sisForm.resetFields();//重置表单
        this.isRepeat = true;
        this.sisForm = {
          name: '',
          status: 1,
          genre: null,
          group: null,
        },
          this.outGenre = [];
        this.qcStandarTableData = []
        this.$emit('update:addVisible', false);
        $('.qctypeVail.errorVail').addClass('is-success').removeClass('is-error')
        this.genreError = false;
      },
      // 关闭弹框 选中情空
      resetTable() {
        this.toggleSelection();
        this.qcStandarShow = false;
        this.qcStandarName = null;
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }

      },

    }
  }

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .el-form .el-form-item {
    display: inline-block;
    width: 49%;
    margin-bottom:12px;
  }

  .el-col-22 .el-select {
    width: 100%;
  }

  .el-form.demo-form-inline {
    padding-top: 15px
  }

  .abilityForm .el-form-item {
    margin-bottom: 10px !important;
  }

  .form {
    height: 170px;
  }

  .elTab {
    height: calc(100% - 170px);
    padding: 0 20px;
  }

  .elTab .el-tabs {
    height: 100%;
  }
</style>
<style>
  .qcStandarAddcon .elTab .el-tabs .el-tabs__content {
    height: calc(100% - 55px)
  }

  .qcStandarAddcon .elTab .el-tabs .el-tab-pane {
    height: 100%;
  }

  .qcStandarAddcon .user-footer {
    height: 35px;
    line-height: 35px;
  }

  .addqcStandarDialog .el-dialog {
    height: 70%;
  }

  .addqcStandarDialog .el-dialog .el-dialog__body {
    height: calc(100% - 85px);
    padding: 15px;
  }

  .addqcStandarDialog .el-dialog .el-dialog__body .heighHalf {
    height: calc(100% - 58px)
  }

  .addqcStandarDialog .el-dialog .el-dialog__body .heighHalf .tableCon {
    height: 100%;
  }

  .addqcStandarDialog .el-dialog .el-dialog__footer {
    height: 45px;
    line-height: 45px;
    padding: 0 20px !important;
  }
  .qctypeVail .el-form-item__label:before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
  }
</style>